import { Component, OnInit } from '@angular/core';
import { UserService } from "../../user/user.service";
import { Router } from "@angular/router";
import {FormBuilder,FormGroup,FormControl,Validators} from '@angular/forms';
import { Observable } from 'rxjs/Observable';
@Component({
  selector: 'app-signup',
  templateUrl: './signup.component.html',
  styleUrls: ['./signup.component.css']
})
export class SignupComponent implements OnInit {
  validateForm:FormGroup;
  alerts: any = [
  ]
  constructor(public userService: UserService, public router: Router,private fb: FormBuilder) {
    this.validateForm = this.fb.group({
      userName: [ '', [ Validators.required ], [ this.userNameAsyncValidator ] ],
      passWord: [ '', [ Validators.required ] ],
      passWordConfirm:['', [ this.passwordConfirmationValidator ]],
      email:['',[ this.emailValidator ]],

    });
  }

  ngOnInit() {
  }
  signup(cred) {
      this.userService.signup(cred).subscribe(data => {
        if (data.json().status == true) {
          this.success(cred);
        } else if (data.json().status == false) {
          this.alerts.push({
            type: 'danger',
            msg: `<strong>Warning!</strong> 已存在用户名！`,
            timeout: 5000
          });
        } else {
          this.alerts.push({
            type: 'danger',
            msg: `<strong>Warning!</strong> 发生未知错误，请联系admin！`,
            timeout: 5000
          });
        }
      })
    
  }

  success(cred) {
    this.userService.login(cred).subscribe(data => {
      if (data.json()[0].status == true) {
        this.userService.setIsLogin('true');
        this.userService.setData(data.json());
        this.router.navigateByUrl('user');
      } else {
        this.alerts.push({
          type: 'danger',
          msg: `<strong>Warning!</strong> 服务器错误啦！`,
          timeout: 5000
        });
        this.userService.setIsLogin('false');
      }
    });
    
  }

  getFormControl(name) {
    return this.validateForm.controls[ name ];
  }

  userNameAsyncValidator = (control: FormControl): any => {
    return Observable.create(function (observer) {
      setTimeout(() => {
        if (control.value === '匿名'||control.value === 'admin'||new RegExp("^[ ]+$").test(control.value)) {
          observer.next({ error: true, duplicated: true });
        } else {
          observer.next(null);
        }
        observer.complete();
      }, 500);
    });
  };

  passwordConfirmationValidator = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return { required: true };
    } else if (control.value !== this.validateForm.controls[ 'passWord' ].value) {
      return { confirm: true, error: true };
    }
  };
  emailValidator = (control: FormControl): { [s: string]: boolean } => {
    const EMAIL_REGEXP = /^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i;
    if (!control.value) {
      return { required: true }
    } else if (!EMAIL_REGEXP.test(control.value)) {
      return { error: true, email: true };
    }
  };
}

